
<template>
  <Dialog
    v-model="dialogVisible"
    :title="t('action.deleteyear')"
    width="280px"
    class="dialogs"
  >
    <el-form
      ref="formRef"
      :model="deleteParams"
      :rules="formRules"
      label-width="auto"
      v-loading="formLoading"
      style="margin-top: 10px"
    >
    <div class="block">
      <el-form-item  prop="year">
      <el-date-picker
        v-model="deleteParams.year"
        type="year"
        value-format = "YYYY"
        :disabled-date="disabledDate"
        :placeholder="t('action.deleteyearinfo')"/>
      </el-form-item>
    </div>

    </el-form>
    <template #footer>
      <el-button
        type="danger"
        :disabled="formLoading"
        @click="deleteByYear">
        {{ t('action.delete') }}
      </el-button>

      <el-button @click="dialogVisible = false">{{ t('action.cancel') }}</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">

import {RtHistoryApi} from "@/api/base/rthistory";

const { t } = useI18n() // 国际化
const message = useMessage(); // 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改


const formRules = reactive({
  year: [{ type:'date', required: true, message: t('action.deleterule'), trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref


const deleteParams = ref({
  year:undefined,
})

const disabledDate = (date) => {
  // 禁用当前年份及之后的年份
  const currentDate = new Date();
  return date.getFullYear() >= currentDate.getFullYear();
};

/** 打开弹窗 */
const open = () => {
  dialogVisible.value = true;
  resetForm();
};
defineExpose({ open }); // 提供 open 方法，用于打开弹窗

const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

/* 年份删除按钮操作 */
const deleteByYear = async () => {
  await formRef.value.validate()
    formLoading.value = true
    const year = deleteParams.value.year
    // 提交请求
    try {
      // 删除的二次确认
      await message.delConfirm(t('action.deleteis'))
      // 发起删除
      await RtHistoryApi.deleteByYear(year)
      message.success(t('common.delSuccess'))
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    } finally {
      formLoading.value = false
    }
}


/** 重置表单 */
const resetForm = () => {
  deleteParams.value = {
    year:undefined,
  }
  formRef.value?.resetFields()
}

</script>


